<template>
	<view>
		<uv-sticky bgColor="#fff">
			<view style="padding: 20rpx;">
				<uv-subsection :list="list" :current="current" custom-style="height: 100rpx;" fontSize="15" activeColor="#333" @change="subChange"></uv-subsection>
			</view>
		</uv-sticky>
		<!-- 共有参数 -->
		<view class="content">
			<view class="unit-name">贷款金额(万元)</view>
			<input :value="loanAmount" type="digit" placeholder="请输入贷款金额"
				@input="(e)=>{loanAmount = e.detail.value,calculateMortgage()}" />
		</view>

		<view class="content">
			<view class="unit-name">贷款年限(年)</view>
			<input :value="loanTerm" type="number" placeholder="请输入贷款期限"
				@input="(e)=>{loanTerm = e.detail.value,calculateMortgage()}" />
		</view>

		<view class="content">
			<view class="unit-name">还款方式</view>
			<picker @change="handlePaymentMethod" :value="pickIndex" range-key="name" :range="paymentRang">
				<view class="unit-value">{{paymentRang[pickIndex].name}}</view>
			</picker>
		</view>

		<!-- 其他特有参数 -->
		<view v-if="selectedLoanType === 'commercial'" class="content">
			<view class="unit-name">商业贷款利率 (%)</view>
			<input :value="commercialRate" type="digit" placeholder="请输入商业贷款利率"
				@input="(e)=>{commercialRate = e.detail.value,calculateMortgage()}" />
		</view>

		<view v-if="selectedLoanType === 'fund'" class="content">
			<view class="unit-name">公积金贷款利率 (%)</view>
			<input :value="fundRate" type="digit" placeholder="请输入公积金贷款利率"
				@input="(e)=>{fundRate = e.detail.value,calculateMortgage()}" />
		</view>

		<template v-if="selectedLoanType === 'combination'">
			<view class="content">
				<view class="unit-name">商业贷款金额 (万元)</view>
				<input :value="combinationCommercialAmount" type="digit" placeholder="请输入商业贷款金额"
					@input="(e)=>{combinationCommercialAmount = e.detail.value,calculateMortgage()}" />
			</view>

			<view class="content">
				<view class="unit-name">公积金贷款金额 (万元)</view>
				<input :value="combinationFundAmount" type="digit" placeholder="请输入公积金贷款金额"
					@input="(e)=>{combinationFundAmount = e.detail.value,calculateMortgage()}" />
			</view>

			<view class="content">
				<view class="unit-name">商业贷款利率 (%)</view>
				<input :value="commercialRate" type="digit" placeholder="请输入商业贷款利率"
					@input="(e)=>{commercialRate = e.detail.value,calculateMortgage()}" />
			</view>

			<view class="content">
				<view class="unit-name">公积金贷款利率 (%)</view>
				<input :value="fundRate" type="digit" placeholder="请输入公积金贷款利率"
					@input="(e)=>{fundRate = e.detail.value,calculateMortgage()}" />
			</view>
		</template>

		<button class="submit" @click="calculateMortgage">计算房贷</button>

		<template v-if="showResult">
			<view class="operator">计算结果</view>

			<view class="content-res">
				<view class="result">
					<view class="label">贷款总额：</view>
					<view>{{ totalLoanAmount }} 元</view>
				</view>

				<view class="result">
					<view class="label">贷款期限：</view>
					<view>{{ loanTerm }} 年 ({{ loanTerm * 12 }} 个月)</view>
				</view>

				<view class="result">
					<view class="label">还款方式：</view>
					<view>{{ repaymentMethod === 'equal-principal-interest' ? '等额本息' : '等额本金' }}</view>
				</view>

				<!-- 等额本息结果 -->
				<template v-if="repaymentMethod === 'equal-principal-interest'">
					<view class="result">
						<view class="label">月供：</view>
						<view class="highlight">{{ monthlyPayment.toFixed(2) }} 元</view>
					</view>

					<view class="result">
						<view class="label">总支付利息：</view>
						<view>{{ totalInterest.toFixed(2) }} 元</view>
					</view>

					<view class="result">
						<view class="label">还款总额：</view>
						<view>{{ totalPayment.toFixed(2) }} 元</view>
					</view>
				</template>

				<!-- 等额本金结果 -->
				<template v-if="repaymentMethod === 'equal-principal'">
					<view class="result">
						<view class="label">首月月供：</view>
						<view class="highlight">{{ firstMonthPayment.toFixed(2) }} 元</view>
					</view>

					<view class="result">
						<view class="label">末月月供：</view>
						<view class="highlight">{{ lastMonthPayment.toFixed(2) }} 元</view>
					</view>

					<view class="result">
						<view class="label">总支付利息：</view>
						<view>{{ totalInterest.toFixed(2) }} 元</view>
					</view>

					<view class="result">
						<view class="label">还款总额：</view>
						<view>{{ totalPayment.toFixed(2) }} 元</view>
					</view>

					<view class="note">注：等额本金还款每月递减 {{ monthlyDecrease.toFixed(2) }} 元</view>
				</template>
			</view>
		</template>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady
	} from '@dcloudio/uni-app'

	const current = ref(0)
	const list = [{
		name: '商业贷款',
		value: "commercial"
	}, {
		name: '公积金贷款',
		value: "fund"
	}, {
		name: '组合贷款',
		value: "combination"
	}]
	const paymentRang = [{
		name: '等额本息',
		value: "equal-principal-interest"
	}, {
		name: '等额本金',
		value: "equal-principal"
	}]
	const pickIndex = ref(0)

	function handlePaymentMethod(e) {
		// console.log('handlePaymentMethod',e)
		pickIndex.value = e.detail.value
		repaymentMethod.value = paymentRang[e.detail.value].value
		calculateMortgage()
	}

	// 点击分段器
	function subChange(index) {
		current.value = index
		selectedLoanType.value = list[index].value
		setTimeout(() => {
			calculateMortgage()
		}, 500)
	}

	// 状态变量
	const selectedLoanType = ref('commercial'); // 默认商业贷款
	const loanAmount = ref(100); // 贷款金额(万元)
	const loanTerm = ref(20); // 贷款期限(年)
	const repaymentMethod = ref('equal-principal-interest'); // 还款方式

	// 利率
	const commercialRate = ref(4.9); // 商业贷款利率(%)
	const fundRate = ref(3.25); // 公积金贷款利率(%)

	// 组合贷款金额
	const combinationCommercialAmount = ref(70); // 组合贷款中的商业贷款金额
	const combinationFundAmount = ref(30); // 组合贷款中的公积金贷款金额

	// 计算结果
	const showResult = ref(false);
	const monthlyPayment = ref(0); // 月供
	const firstMonthPayment = ref(0); // 首月月供
	const lastMonthPayment = ref(0); // 末月月供
	const totalInterest = ref(0); // 总利息
	const totalPayment = ref(0); // 还款总额
	const monthlyDecrease = ref(0); // 每月递减金额

	// 计算组合贷款总额
	const totalLoanAmount = computed(() => {
		if (selectedLoanType.value === 'combination') {
			return (combinationCommercialAmount.value + combinationFundAmount.value) * 10000;
		}
		return loanAmount.value * 10000;
	});

	// 当切换到组合贷款时，同步金额
	watch(selectedLoanType, (newVal) => {
		console.log('newVal', newVal)
		if (newVal === 'combination') {
			combinationCommercialAmount.value = Math.floor(loanAmount.value * 0.7);
			combinationFundAmount.value = loanAmount.value - combinationCommercialAmount.value;
		}
	});

	// 计算房贷
	const calculateMortgage = () => {
		// 验证输入
		if (!validateInput()) return;

		// 根据贷款类型计算
		if (selectedLoanType.value === 'commercial') {
			calculateCommercialLoan();
		} else if (selectedLoanType.value === 'fund') {
			calculateFundLoan();
		} else {
			calculateCombinationLoan();
		}

		showResult.value = true;
	};

	// 验证输入
	const validateInput = () => {
		// 基本验证
		if (!loanAmount.value || loanAmount.value <= 0) {
			uni.showToast({
				title: '请输入有效的贷款金额',
				icon: "none"
			});
			return false;
		}

		if (!loanTerm.value || loanTerm.value <= 0 || loanTerm.value > 30) {
			uni.showToast({
				title: '请输入有效的贷款期限（1-30年）',
				icon: "none"
			});
			return false;
		}

		// 组合贷款验证
		if (selectedLoanType.value === 'combination') {
			if (!combinationCommercialAmount.value || combinationCommercialAmount.value <= 0) {
				uni.showToast({
					title: '请输入有效的商业贷款金额',
					icon: "none"
				});
				return false;
			}

			if (!combinationFundAmount.value || combinationFundAmount.value <= 0) {
				uni.showToast({
					title: '请输入有效的公积金贷款金额',
					icon: "none"
				});
				return false;
			}

			if (combinationCommercialAmount.value + combinationFundAmount.value != loanAmount.value) {
				uni.showToast({
					title: '商业贷款金额与公积金贷款金额之和应等于总贷款金额',
					icon: "none"
				});
				return false;
			}
		}

		return true;
	};

	// 计算商业贷款
	const calculateCommercialLoan = () => {
		const principal = loanAmount.value * 10000; // 贷款本金(元)
		const months = loanTerm.value * 12; // 贷款总月数
		const monthlyRate = commercialRate.value / 100 / 12; // 月利率

		if (repaymentMethod.value === 'equal-principal-interest') {
			// 等额本息
			// 月供 = 本金 × 月利率 × (1+月利率)^还款月数 / [(1+月利率)^还款月数 - 1]
			monthlyPayment.value = principal * monthlyRate * Math.pow(1 + monthlyRate, months) /
				(Math.pow(1 + monthlyRate, months) - 1);
			totalPayment.value = monthlyPayment.value * months;
			totalInterest.value = totalPayment.value - principal;
		} else {
			// 等额本金
			const monthlyPrincipal = principal / months; // 每月应还本金
			let totalInterestSum = 0;

			// 首月利息
			const firstMonthInterest = principal * monthlyRate;
			firstMonthPayment.value = monthlyPrincipal + firstMonthInterest;

			// 最后一个月利息
			const lastMonthInterest = monthlyPrincipal * monthlyRate;
			lastMonthPayment.value = monthlyPrincipal + lastMonthInterest;

			// 总利息 = (首月利息 + 末月利息) × 月数 / 2
			totalInterest.value = (firstMonthInterest + lastMonthInterest) * months / 2;
			totalPayment.value = principal + totalInterest.value;

			// 每月递减金额
			monthlyDecrease.value = monthlyPrincipal * monthlyRate;
		}
	};

	// 计算公积金贷款
	const calculateFundLoan = () => {
		const principal = loanAmount.value * 10000; // 贷款本金(元)
		const months = loanTerm.value * 12; // 贷款总月数
		const monthlyRate = fundRate.value / 100 / 12; // 月利率

		if (repaymentMethod.value === 'equal-principal-interest') {
			// 等额本息
			monthlyPayment.value = principal * monthlyRate * Math.pow(1 + monthlyRate, months) /
				(Math.pow(1 + monthlyRate, months) - 1);
			totalPayment.value = monthlyPayment.value * months;
			totalInterest.value = totalPayment.value - principal;
		} else {
			// 等额本金
			const monthlyPrincipal = principal / months; // 每月应还本金

			// 首月利息
			const firstMonthInterest = principal * monthlyRate;
			firstMonthPayment.value = monthlyPrincipal + firstMonthInterest;

			// 最后一个月利息
			const lastMonthInterest = monthlyPrincipal * monthlyRate;
			lastMonthPayment.value = monthlyPrincipal + lastMonthInterest;

			// 总利息
			totalInterest.value = (firstMonthInterest + lastMonthInterest) * months / 2;
			totalPayment.value = principal + totalInterest.value;

			// 每月递减金额
			monthlyDecrease.value = monthlyPrincipal * monthlyRate;
		}
	};

	// 计算组合贷款
	const calculateCombinationLoan = () => {
		const commercialPrincipal = combinationCommercialAmount.value * 10000; // 商业贷款本金
		const fundPrincipal = combinationFundAmount.value * 10000; // 公积金贷款本金
		const months = loanTerm.value * 12; // 贷款总月数

		const commercialMonthlyRate = commercialRate.value / 100 / 12; // 商业贷款月利率
		const fundMonthlyRate = fundRate.value / 100 / 12; // 公积金贷款月利率

		if (repaymentMethod.value === 'equal-principal-interest') {
			// 等额本息：分别计算两部分月供，然后相加
			const commercialMonthly = commercialPrincipal * commercialMonthlyRate * Math.pow(1 + commercialMonthlyRate,
					months) /
				(Math.pow(1 + commercialMonthlyRate, months) - 1);

			const fundMonthly = fundPrincipal * fundMonthlyRate * Math.pow(1 + fundMonthlyRate, months) /
				(Math.pow(1 + fundMonthlyRate, months) - 1);

			monthlyPayment.value = commercialMonthly + fundMonthly;
			totalPayment.value = monthlyPayment.value * months;
			totalInterest.value = totalPayment.value - (commercialPrincipal + fundPrincipal);
		} else {
			// 等额本金
			const commercialMonthlyPrincipal = commercialPrincipal / months;
			const fundMonthlyPrincipal = fundPrincipal / months;
			const totalMonthlyPrincipal = commercialMonthlyPrincipal + fundMonthlyPrincipal;

			// 首月利息
			const commercialFirstInterest = commercialPrincipal * commercialMonthlyRate;
			const fundFirstInterest = fundPrincipal * fundMonthlyRate;
			firstMonthPayment.value = totalMonthlyPrincipal + commercialFirstInterest + fundFirstInterest;

			// 最后一个月利息
			const commercialLastInterest = commercialMonthlyPrincipal * commercialMonthlyRate;
			const fundLastInterest = fundMonthlyPrincipal * fundMonthlyRate;
			lastMonthPayment.value = totalMonthlyPrincipal + commercialLastInterest + fundLastInterest;

			// 总利息
			const commercialTotalInterest = (commercialFirstInterest + commercialLastInterest) * months / 2;
			const fundTotalInterest = (fundFirstInterest + fundLastInterest) * months / 2;
			totalInterest.value = commercialTotalInterest + fundTotalInterest;
			totalPayment.value = (commercialPrincipal + fundPrincipal) + totalInterest.value;

			// 每月递减金额
			monthlyDecrease.value = (commercialMonthlyPrincipal * commercialMonthlyRate) +
				(fundMonthlyPrincipal * fundMonthlyRate);
		}
	}
</script>

<style>
	@import "house.css"
</style>